<template>
  <div class="login">
    <div class="login-logo"></div>
    <div class="login-container">
      <div class="login-bg"></div>
      <div class="login-form">
        <h3>登录</h3>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px">
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              type="text" 
              auto-complete="off" 
              placeholder="请输入账号"
              class="login-form-input"
              @change="onChangeAccount"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              auto-complete="off" 
              placeholder="请输入密码" 
              @keyup.enter.native="handleLogin"
              class="login-form-input"
            />
          </el-form-item>
          <el-form-item prop="pharmacyId">
            <el-select 
              v-model="loginForm.pharmacyId" 
              placeholder="请选择门店"
              class="login-form-input"
              popper-class="login-form-select"
            > 
              <template v-for="item in scoreList">
                <el-option :key="item.value" :label="item.label" :value="item.value"></el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item prop="code" class="form-item-code">
            <el-input 
              v-model="loginForm.code" 
              auto-complete="off" 
              placeholder="验证码" 
              style="width: 63%"
              @keyup.enter.native="handleLogin"
              class="login-form-input"
            >
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode">
            </div>
          </el-form-item>
          <el-checkbox class="login-checkbox" v-model="loginForm.rememberMe">
            记住我
          </el-checkbox>
          <el-form-item :style="btnStyle">
            <el-button 
              :loading="loading" 
              size="medium" 
              type="primary" 
              class="login-form-button" 
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="login-his">诊所系统</div>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import Config from '@/settings'
import { getCodeImg, queryStore } from '@/api/login'
import Cookies from 'js-cookie'

export default {
  name: 'Login',
  data() {
    let result = {
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        pharmacyId: '',
        code: '',
        uuid: ''
      },
      loading: false,
      redirect: undefined,
      scoreList: [],
      query: {}
    };
    let checkName = ((rule, value, callback) => {
      if(!value) {
        callback(new Error("用户名不能为空"));
        return;
      } else if(value && result.loginForm.pharmacyId) {
        callback();
        return;
      }
      result.scoreList = [];
      queryStore(value).then(res => {
        if(!res.success) {
          callback(new Error("登录账号错误"));
        }
        res.list.forEach(store => {
          result.scoreList.push({
            value: store.id,
            label: store.storeName
          });
        });
        result.loginForm.pharmacyId = result.scoreList.length ? result.scoreList[0].value : null;
        callback();
      }).catch(() => {
        callback(new Error("系统异常"));
      });
    });
    result["loginRules"] = {
      username: [
        { validator: checkName, trigger: 'blur' }
      ],
      password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
      code: [{ required: true, trigger: 'change', message: '验证码不能为空' }],
      pharmacyId: [{ required: true, trigger: 'blur', message: '请选择门店' }]
    };
    return result;
  },
  computed: {
    btnStyle() {
      let res = {
        width: "100%"
      }
      if(!this.showPharmacy) {
        res["margin-top"] = "35px";
      }
      return res;
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
        
        // redirect路径携带参数
        if(route.query) {
          for(let key in route.query) {
            if(key === "redirect") continue;
            this.query[key] = route.query[key];
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
  },
  mounted() {
    if(this.loginForm.username) {
      this.$refs.loginForm.validateField(["username"]);
    }
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? '' : password
      password = password === undefined ? this.loginForm.password : password
      
      this.loginForm.username = username === undefined ? this.loginForm.username : username
      this.loginForm.password = password
      this.loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)
      this.loginForm.code = ''
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          pharmacyId: this.loginForm.pharmacyId,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        }
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password)
        }
        if (valid) {
          this.loading = true
          if (user.rememberMe) {
            Cookies.set('username', user.username, { expires: Config.passCookieExpires })
            Cookies.set('password', user.password, { expires: Config.passCookieExpires })
            Cookies.set('rememberMe', user.rememberMe, { expires: Config.passCookieExpires })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch('Login', user).then(() => {
            this.loading = false
            this.$router.push({ path: this.redirect || '/dashboard', query: this.query })
          }).catch(() => {
            this.loading = false
            this.getCode()
          })
        } else {
          return false
        }
      })
    },
    onChangeAccount() {
      this.loginForm.pharmacyId = null;
    }
  }
}
</script>

<style>
.login {
  background-image: url(../assets/images/bg.jpeg);
  justify-content: center;
  align-items: center;
  position: relative;
  display: flex;
  height: 100%;
}

.login .login-container {
  display: flex;
}

.login .login-logo,
.login .login-his {
  position: absolute;
  color: #FFF;
  width: 100%;
  left: 0;
}

.login .login-logo {
  background-size: cover;
  width: 232px;
  height: 68px;
  left: 60px;
  top: 65px;
}

.login .login-his {
  text-align: center;
  font-size: 22px;
  bottom: 35px;
}

.login .login-bg {
  height: 587px;
  margin: auto;
  width: 768px;
}

.login .login-form {
  background-color: #FFF;
  padding: 25px 35px;
  margin-left: 45px;
  width: 500px;
}

.login .login-form h3 {
  font-size: 30px;
}

.login .login-form .login-form-input {
  width: 100%;
}

.login .login-form .login-form-input .el-input__inner {
  border: 0 none;
  border-bottom: 1px solid #F6F6F6;
  font-size: 20px;
  height: 60px;
}

.login .login-form .el-form-item__error {
  padding-left: 18px;
  font-size: 14px;
}

.login .form-item-code .el-form-item__content {
  align-items: center;
  display: flex;
}

.login .login-form .login-code {
  display: inline-block;
  margin-left: 10px;
  height: 38px;
  width: 33%;
}

.login .login-form .login-code img {
  vertical-align: middle;
  cursor: pointer;
}

.login .login-form-button {
  background-color: #5fb7f5;
  border: 0 none;
  height: 60px;
  width: 100%;
}

.login .login-checkbox {
  margin-bottom: 15px;
  margin-left: 5px;
}

.login-form-select .el-select-dropdown__item {
  line-height: 45px;
  height: 45px;
}
</style>